package com.ruoyi.zxjd.work.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.zxjd.common.CommonConstants;
import com.ruoyi.zxjd.work.domain.BaseWorkTemplateTable;
import com.ruoyi.zxjd.work.domain.WorkArrange;
import com.ruoyi.zxjd.work.domain.WorkProgress;
import com.ruoyi.zxjd.work.mapper.WorkArrangeMapper;
import com.ruoyi.zxjd.work.mapper.WorkHandleMapper;
import com.ruoyi.zxjd.work.mapper.WorkProgressMapper;
import com.ruoyi.zxjd.work.service.IWorkProgressService;
import com.ruoyi.zxjd.work.service.IWorkTemplateTable7Service;
import com.ruoyi.zxjd.work.service.IWorkTemplateTable8Service;
import com.ruoyi.zxjd.work.service.IWorkTemplateTable9Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

/**
 * 工作进度Service业务层处理
 *
 * @author lcc
 * @date 2021-01-26
 */
@Service
public class WorkProgressServiceImpl implements IWorkProgressService {
    @Autowired
    private WorkProgressMapper workProgressMapper;
    @Autowired
    private WorkArrangeMapper workArrangeMapper;
    @Autowired
    private WorkHandleMapper workHandleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IWorkTemplateTable7Service workTemplateTable7Service;
    @Autowired
    private IWorkTemplateTable8Service workTemplateTable8Service;
    @Autowired
    private IWorkTemplateTable9Service workTemplateTable9Service;


    /**
     * 查询工作进度
     *
     * @param progressId 工作进度ID
     * @return 工作进度
     */
    @Override
    public WorkProgress selectWorkProgressById(Long progressId) {
        return workProgressMapper.selectWorkProgressById(progressId);
    }

    /**
     * 查询工作进度列表
     *
     * @param workProgress 工作进度
     * @return 工作进度
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<WorkProgress> selectWorkProgressList(WorkProgress workProgress) {
        return workProgressMapper.selectWorkProgressList(workProgress);
    }

    /**
     * 新增工作进度
     *
     * @param workProgress 工作进度
     * @return 结果
     */
    @Override
    public int insertWorkProgress(WorkProgress workProgress) {
        workProgress.setCreateBy(ShiroUtils.getLoginName());
        workProgress.setCreateTime(DateUtils.getNowDate());
        workProgress.setUpdateBy(ShiroUtils.getLoginName());
        workProgress.setUpdateTime(DateUtils.getNowDate());
        return workProgressMapper.insertWorkProgress(workProgress);
    }

    /**
     * 修改工作进度
     *
     * @param workProgress 工作进度
     * @return 结果
     */
    @Override
    public int updateWorkProgress(WorkProgress workProgress) {
        workProgress.setUpdateBy(ShiroUtils.getLoginName());
        workProgress.setUpdateTime(DateUtils.getNowDate());
        return workProgressMapper.updateWorkProgress(workProgress);
    }

    /**
     * 删除工作进度对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteWorkProgressByIds(String ids) {
        int total = workProgressMapper.deleteWorkProgressByIds(Convert.toStrArray(ids));
        workProgressMapper.deleteWorkFormByIds(Convert.toStrArray(ids));
        // 异步更新工作安排填报人数
        AsyncManager.me().execute(updateTotal());
        return total;
    }

    public TimerTask updateTotal() {
        return new TimerTask() {
            @Override
            public void run() {
                List<Map<String, Object>> list = workProgressMapper.selectTotalGroupByArrangId();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        WorkArrange workArrange = new WorkArrange();
                        workArrange.setArrangeId(Long.parseLong(list.get(i).get("arrange_id") + ""));
                        workArrange.setTotal(Integer.parseInt(list.get(i).get("total") + ""));
                        workArrange.setUnfillTotal(Integer.parseInt(list.get(i).get("unfill_total") + ""));
                        workArrangeMapper.updateWorkArrange(workArrange);
                    }
                }
            }
        };
    }

    /**
     * 删除工作进度信息
     *
     * @param progressId 工作进度ID
     * @return 结果
     */
    @Override
    public int deleteWorkProgressById(Long progressId) {
        return workProgressMapper.deleteWorkProgressById(progressId);
    }

    /**
     * 接收工作任务
     *
     * @param progressId 工作进度ID
     * @return 结果
     */
    @Override
    public int receiveTask(Long progressId) {
        WorkProgress workProgress = workProgressMapper.selectWorkProgressById(progressId);
        workProgress.setStatus(CommonConstants.TO_BE_FILLED_IN);
        workProgress.setReceiveDate(DateUtils.getNowDate());
        return this.updateWorkProgress(workProgress);
    }

    /**
     * 提交工作任务
     *
     * @param ids 工作进度IDS
     * @return 结果
     */
    @Override
    public int updateWorkProgressStatusByIds(String ids) {
        String status = CommonConstants.REPORTED;
        return workProgressMapper.updateWorkProgressStatusByIds(Convert.toStrArray(ids), status);
    }

    /**
     * 通过工作安排ID查询工作进度列表
     *
     * @param arrangeId 工作安排ID
     * @param related   是否关联查询
     * @return 工作进度列表
     */
    @Override
    public List<WorkProgress> selectWorkProgressListByArrangeId(Long arrangeId, Boolean related) {
        return workProgressMapper.selectWorkProgressListByArrangeId(arrangeId, related);
    }

    /**
     * 校验提交日期并更新工作进度状态
     *
     * @param workProgress
     */
    public int validate(WorkProgress workProgress) {
        WorkProgress oldWorkProgress = workProgressMapper.selectWorkProgressById(workProgress.getProgressId());
        if (StringUtils.equals(CommonConstants.REPORTED, workProgress.getStatus())) {
            String nowDate = DateUtils.getDate();
            String endDate = DateUtils.parseDateToStr("yyyy-MM-dd", oldWorkProgress.getEndDate());
            if (StringUtils.compare(nowDate, endDate) > 0) {
                workProgress.setStatus(CommonConstants.OVERDUE_REPORTED);
            }
            // 更新上报人数
            workArrangeMapper.updateUnfillTotal(oldWorkProgress.getArrangeId(), -1);
            // 更新未处理项
            workHandleMapper.updateUntreatedTotal(oldWorkProgress.getReceiveUserId(), CommonConstants.WORK, -1);
        }
        return this.updateWorkProgress(workProgress);
    }

    /**
     * 退回重填
     *
     * @param progressId 工作进度ID
     * @return 结果
     */
    @Override
    public int refillTask(Long progressId) {
        WorkProgress workProgress = workProgressMapper.selectWorkProgressById(progressId);
        workProgress.setStatus(CommonConstants.RETURNED);
        workArrangeMapper.updateUnfillTotal(workProgress.getArrangeId(), 1);
        workHandleMapper.updateUntreatedTotal(workProgress.getReceiveUserId(), CommonConstants.WORK, 1);
        return this.updateWorkProgress(workProgress);
    }


    /**
     * 短信提示
     *
     * @param progressId 工作进度ID
     * @return 结果
     */
    @Override
    public int smsPrompt(Long progressId) {
        WorkProgress workProgress = workProgressMapper.selectWorkProgressById(progressId);
        SysUser user = sysUserMapper.selectUserById(workProgress.getReceiveUserId());
        String message = user.getUserName() + "，您好！在线监督平台提示: 您有一项工作任务(" + workProgress.getArrangeTitle() + ")待上报";
        String mobileNo = user.getPhonenumber();
        SmsUtil.sendMessage(message, mobileNo);
        return 1;
    }


    /**
     * 查询机构管理树
     * 1.查询任务信息
     * 2.根据任务安排内容
     * 3.获取节点信息
     *
     * @param progressId 工作进度id
     * @return 所有机构信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectTemplateTree(Long progressId) {
        WorkProgress workProgress = workProgressMapper.selectWorkProgressById(progressId);
        WorkArrange workArrange = workArrangeMapper.selectWorkArrangeById(workProgress.getArrangeId());

        List<BaseWorkTemplateTable> baseWorkTemplateTables = getBaseWorkTemplateTables(progressId, workArrange);

        List<Ztree> ztrees = initZtree(baseWorkTemplateTables, workArrange);
        return ztrees;
    }

    /**
     *  根据任务进度id和任务安排, 查询已经完成的工作模板列表
     * @param progressId 工作进度id
     * @param workArrange 工作安排
     * @return
     */
    private List<BaseWorkTemplateTable> getBaseWorkTemplateTables(Long progressId, WorkArrange workArrange) {
        Integer templateId = workArrange.getTemplateId().intValue();

        List<BaseWorkTemplateTable> baseWorkTemplateTables = null;
        switch (templateId) {
            case 7:
                baseWorkTemplateTables = (List<BaseWorkTemplateTable>) (List) workTemplateTable7Service.selectWorkTemplateTable7ByProgressId(progressId);
                break;
            case 8:
                baseWorkTemplateTables = (List<BaseWorkTemplateTable>) (List) workTemplateTable8Service.selectWorkTemplateTable8ByProgressId(progressId);
                break;
            case 9:
                baseWorkTemplateTables = (List<BaseWorkTemplateTable>) (List) workTemplateTable9Service.selectWorkTemplateTable9ByProgressId(progressId);
                break;
            default:
                throw new RuntimeException("参数错误");
        }
        return baseWorkTemplateTables;
    }


    /**
     * 对象转机构树
     *
     * @param workTemplateTableList 工作填报
     * @param workProgress          工作进度
     * @return 树结构列表
     */
    private List<Ztree> initZtree(List<BaseWorkTemplateTable> workTemplateTableList, WorkArrange workProgress) {

      List<Ztree> ztrees = new ArrayList<Ztree>();
        int index = 1;
        for (BaseWorkTemplateTable baseWorkTemplateTable : workTemplateTableList) {
                Ztree ztree = new Ztree();
                ztree.setId(baseWorkTemplateTable.getId());
//                ztree.setpId(workProgress.getArrangeId());
//                ztree.setName(baseWorkTemplateTable.getVal1());
                ztree.setTitle(workProgress.getArrangeTitle());
                ztrees.add(ztree);
                index++;
        }

        return ztrees;
    }
}
